<template>
  <el-card class="layout-query">
    <el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
      <el-form-item prop="title">
        <el-input v-model="state.queryForm.title" placeholder="根据题目名称查询"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="RefreshRight" @click="reset(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card>
    <el-space>
      <el-space>
        <el-button icon="Plus" type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-space>
      <el-space>
        <el-button icon="Delete" plain type="danger" @click="deleteBatchHandle()">批量删除</el-button>
      </el-space>
    </el-space>
    <el-table
      v-loading="state.dataListLoading"
      show-overflow-tooltip
      :data="state.dataList"
      border
      class="layout-table"
      max-height="calc(100vh - var(--theme-header-height) - 40px - 225px)"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50" />
      <el-table-column type="index" label="序号" align="center" width="70" />
      <el-table-column prop="title" label="题目标题" align="left" />
      <el-table-column prop="content" label="题目内容" align="left" />
      <el-table-column prop="answer" label="题目答案" align="left" />
      <el-table-column label="题目难度" align="center" width="100">
        <template #default="{ row }">
          {{ difficultyMap.get(row.difficulty?.toString()) || '未知' }}
        </template>
      </el-table-column>
      <el-table-column 
        prop="questionCategoryId" 
        label="题目分类" 
        align="center" 
        width="100"
      >
        <template #default="{ row }">
          {{ categoryMap.get(row.questionCategoryId) || '未知' }}
        </template>
      </el-table-column>
      <el-table-column prop="tagIdList" label="题目标签" header-align="center" align="left" >
        <template #default="{ row }">
          <el-tag
            v-for="tagId in row.tagIdList"
            :key="tagId"
            type="primary"
            effect="light"
            class="mx-1!"
            >
              {{ tagIdToNameMap.get(tagId) || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="题目状态" align="center" width="100">
        <template #default="{ row }">
          {{ statusMap.get(row.status?.toString()) || '未知' }}
        </template>
      </el-table-column>
      <el-table-column prop="isVip" label="VIP专属" align="center" width="100">
        <template #default="{ row }">
          {{ vipMap.get(row.isVip?.toString()) || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="150">
        <template #default="{ row }">
          <el-button type="primary" link @click="addOrUpdateHandle(row as ListVO)">修改</el-button>
          <el-button type="danger" link @click="deleteBatchHandle((row as ListVO).id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="state.current"
      :page-sizes="state.pageSizes"
      :page-size="state.pageSize"
      :total="state.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />

    <!-- 弹窗, 新增 / 修改 -->
    <AddOrUpdate 
      ref="addOrUpdateRef" 
      @refresh-data-list="getDataList"
      :difficultyMap="difficultyMap"
      :statusMap="statusMap"
      :vipMap="vipMap"
      />
  </el-card>
</template>

<script setup lang="ts" name="SysTagIndex">
import { reactive, ref, computed, provide } from 'vue'

import { useCrud } from '@/hooks/useCrud'
import { useDict } from '@/hooks/useDict'

import AddOrUpdate from './components/AddOrUpdate.vue'

import { IHooksOptions } from '@/hooks/useCrud/data.d'
import { DictTypes,ListVO, SearchDTO } from './data.d'

import { DictHooksOptions } from '@/hooks/useDict/data'

import { getQuestionCategoryList, getQuestionTagList } from './api'

// 获取题目列表
const state: IHooksOptions<SearchDTO, ListVO> = reactive({
  dataListUrl: '/code-duck-question/listByQuestionCategory',
  deleteUrl: '/code-duck-question/delete',
  primaryKey: 'id',
  queryForm: {
    //name: '',
    title: '',
  },
})

const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle, reset } =
  useCrud(state)

const queryRef = ref()
const addOrUpdateRef = ref()
const addOrUpdateHandle = (row?: ListVO) => {
  addOrUpdateRef.value.init(row)
}

// 存储题目分类数据
const categoryData = ref<{ id: string; name: string }[]>([])
// 调用封装的 API 方法获取题目分类列表
getQuestionCategoryList().then(res => {
  categoryData.value = (res.data as any).records
})

// 计算属性，生成分类 id 到 name 的映射
const categoryMap = computed(() => {
  const map = new Map<string, string>()
  categoryData.value.forEach((category) => {
    if (category.id && category.name) {
      map.set(category.id, category.name)
    }
  })
  return map
})

// 存储题目标签数据
const tagData = ref<{ id: string; name: string; children: { id: string; name: string }[] }[]>([])
const secondTagData = ref<{ id: string; name: string }[]>([])
// 题目标签列表
getQuestionTagList().then(res => {
  tagData.value = (res.data as any).records.map((item:any) => ({
    id: item.id,
    name: item.name,
    children: item.secondCodeDuckTagList.map((tag:any) => ({
      id: tag.id,
      name: tag.name,
    })),
  }))
  secondTagData.value = tagData.value.flatMap((item) => item.children)
})

// 标签映射
const tagIdToNameMap = computed(() => {
  const map = new Map<string, string>()
  secondTagData.value.forEach((item) => {
    map.set(item.id, item.name)
  })
  return map
})

// 创建dictState，并执行useDict
const dictState: DictHooksOptions<DictTypes> = reactive({
  dictTypeList: ['question_difficulty', 'question_status', 'user_vip_flag'],
})
const { getDictList } = useDict(dictState)

// 难度映射
const difficultyMap = computed(() => {
  const map = new Map<string, string>()
  const difficultyDict = dictState.dictMap?.['question_difficulty'] ?? []
  difficultyDict.forEach((item) => {
    if (item.itemValue && item.itemLabel) {
      map.set(item.itemValue, item.itemLabel)
    }
  })
  return map
})
// 状态映射
const statusMap = computed(() => {
  const map = new Map<string, string>()
  const statusDict = dictState.dictMap?.['question_status'] ?? []
  statusDict.forEach((item) => {
    if (item.itemValue && item.itemLabel) {
      // 给 itemValue 双引号内添加单引号
      const modifiedValue = `'${item.itemValue}'`
      map.set(modifiedValue, item.itemLabel)
    }
  })
  return map
})
// VIP映射
const vipMap = computed(() => {
  const map = new Map<string, string>()
  const vipDict = dictState.dictMap?.['user_vip_flag'] ?? []
  vipDict.forEach((item) => {
    if (item.itemValue && item.itemLabel) {
      map.set(item.itemValue, item.itemLabel)
    }
  })
  return map
})

provide('tagData',tagData)
</script>
<style scoped>
.layout-table :deep(.el-table__body-wrapper .el-checkbox) {
  display: flex;
  justify-content: center;
  width: 100%;
}
</style>